package d01_reflect_use;

import java.io.*;
import java.lang.reflect.Field;

public class Test {
    public static void saveObject(Object obj) {
        try (
                OutputStream os = new FileOutputStream(
                        "D:\\javabase_ws\\javaAdvanceProject\\day16_reflect_annotation_proxy\\src\\d01_reflect_use\\objects.txt",
                        true);
                BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os))
        ) {
            // 获取obj对象对应的字节码文件
            Class<?> clazz = obj.getClass();
            Field[] fields = clazz.getDeclaredFields();

            bw.write("============" + clazz.getSimpleName() + "============");
            bw.newLine(); // 换行

            for (Field field : fields) {
                field.setAccessible(true);
                String fieldName = field.getName();
                Object fieldValue = field.get(obj);
                bw.write(fieldName + "=" + fieldValue);
                bw.newLine(); // 每个字段后换行

                System.out.println(fieldName + "=" + fieldValue);
            }
            bw.newLine(); // 对象之间空一行

        } catch (IOException | IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        saveObject(new Cat("Tom", 3, 5));
        saveObject(new Student("Alice", 20, 90));
    }
}
